package com.william.doc;

import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class DocConverter {
    
    /**
     * 获取目录下所有docx文件
     * @param dirPath 目录路径
     * @return docx文件列表
     */
    public List<Path> getDocxFiles(String dirPath) throws IOException {
        return Files.walk(Paths.get(dirPath))
                .filter(Files::isRegularFile)
                .filter(path -> path.toString().toLowerCase().endsWith(".docx"))
                .collect(Collectors.toList());
    }

    /**
     * 将docx文件转换为markdown
     * @param docxPath docx文件路径
     * @return 是否转换成功
     */
    public boolean convertToMarkdown(Path docxPath) {
        try {
            // 构建输出路径，与原文件同目录，仅改变扩展名
            String outputPath = docxPath.toString().replaceAll("\\.docx$", ".md");
            
            // 构建pandoc命令
            ProcessBuilder processBuilder = new ProcessBuilder(
                "pandoc",
                "-f", "docx",
                "-t", "markdown",
                "-o", outputPath,
                docxPath.toString()
            );
            
            // 执行命令
            Process process = processBuilder.start();
            int exitCode = process.waitFor();
            
            if (exitCode == 0) {
                log.info("Successfully converted {} to markdown", docxPath);
                return true;
            } else {
                log.error("Failed to convert {} to markdown, exit code: {}", docxPath, exitCode);
                return false;
            }
            
        } catch (IOException | InterruptedException e) {
            log.error("Error converting file: " + docxPath, e);
            return false;
        }
    }
} 